'''
Development Task 

The development task generates a phenotype using the parameters in the genotype.
'''
import os
import time
import random

from dexen import BaseSlaveTask

from slave_tasks import common
from individual import Individual

common.enable_hou_module()
import hou

#Function to run Houdini
def run_houdini_dev(ind):
    #open the hipnc file
    hou_file_path = os.path.join(common.HOU_FOLDER_PATH, common.HOU_DEV_FILE_NAME)
    hou.hipFile.load(hou_file_path)
    #set the parameters using the individual's genes
    genotype_node = hou.node(common.GENOTYPE_NODE_PATH)
    for i in range(len(ind.genotype)):
        genotype_node.setParms({"gene_"+str(i+1):ind.genotype[i]})
    #save phenotype to file
    phen_folder_path = os.path.join(common.HOU_FOLDER_PATH, "temp")
    common.create_folder(phen_folder_path)
    phen_file_path = os.path.join(phen_folder_path, "temp.bgeo")
    phenotype_node = hou.node(common.PHENOTYPE_NODE_PATH)
    phenotype_node.setParms(dict([["file",phen_file_path]]))
    phenotype_node.cook()
    #read the phenotype file
    f = open(phen_file_path, "rb")
    phenotype = f.read()
    f.close()
    #return the phenotype (as a string)
    return phenotype
    
#Slave task for development
class DevTask(BaseSlaveTask):
    def __init__(self):
        pass
    def __execute__(self, master_state, inds):
        #process individuals
        for ind in inds:
            assert isinstance(ind, Individual)
            ind.phenotype = run_houdini_dev(ind)
            ind.archive_data("genotype.txt", str(ind.genotype))
            ind.archive_data("phenotype.txt", "phenotype length = " + str(len(ind.phenotype)))
        #return the inds with the phenotype added
        return inds


